package com.eastcom.collection.tools.common

/**
 * Created by yuanyue on 2014-08-06.
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.logging.Logger;

public class ShellExecutor {
    private Logger _log = Logger.getLogger(getClass().getName());
    private File execScriptFile = null;
    private Process subProcess = null;
    private String command = "";
    private boolean isFile = true;

    public ShellExecutor(File execScriptFile) {
        this.execScriptFile = execScriptFile;
    }

    public Process getProcessObject() {
        return subProcess;
    }

    public ShellExecutor(String execScript) {
        this(execScript != null ? new File(execScript) : null);
    }

    public ShellExecutor(String cmd, boolean isFile) {
        if (isFile) {
            this.execScriptFile = (cmd != null ? new File(cmd) : null);
        } else {
            this.isFile = false;
            command = cmd;
        }
    }

    public boolean exec() {
        return exec("");
    }

    public boolean exec(String param) {
        return exec(param, null);
    }

    public boolean exec(String[] envp) {
        return exec("", envp);
    }

    public boolean exec(String param, String[] envp) {
        if (!isFile) {
            try {
                _log.finest("Rutime exec command: " + command + " " + param);
                subProcess = Runtime.getRuntime().exec(command + " " + param,
                        envp);
                processStream(subProcess);

                return true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }
        if (execScriptFile == null) {
            throw new NullPointerException();
        }
        if (execScriptFile.exists()) {
            try {
                _log.finest("Rutime exec command: " + execScriptFile.getPath()
                        + " " + param);
                Process process = Runtime.getRuntime().exec(
                        execScriptFile.getPath() + " " + param, envp);
                processStream(process);
                return true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    public boolean WaitForExec(String params) {
        if (execScriptFile == null) {
            throw new NullPointerException();
        }
        if (execScriptFile.exists()) {
            try {
                Process process = Runtime.getRuntime().exec(
                        execScriptFile.getPath() + " " + params);
                processStream(process);

                try {
                    int exitValue = process.waitFor();
                    if (exitValue == 0) {
                        return true;
                    } else {
                        return false;
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    process.destroy();
                    return false;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    public boolean WaitForExec() {
        if (execScriptFile == null) {
            throw new NullPointerException();
        }
        if (execScriptFile.exists()) {
            try {
                Process process = Runtime.getRuntime().exec(
                        execScriptFile.getPath());
                processStream(process);

                try {
                    int exitValue = process.waitFor();
                    if (exitValue == 0) {
                        return true;
                    } else {
                        return false;
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    process.destroy();
                    return false;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    private void processStream(Process process) {
        final BufferedReader bufferedReaderError = new BufferedReader(
                new InputStreamReader(process.getErrorStream()));
        Thread threadError = new Thread() {
            public void run() {
                String str = "";
                try {
                    while ((str = bufferedReaderError.readLine()) != null) {
                        System.out.println(str);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        final BufferedReader bufferedReaderInput = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        Thread threadInput = new Thread() {
            public void run() {
                String str = "";
                try {
                    while ((str = bufferedReaderInput.readLine()) != null) {
                        System.out.println(str);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        // final BufferedReader bufferedReader = new BufferedReader(
        // new InputStreamReader(System.in));
        // final OutputStream os = process.getOutputStream();
        // Thread threadOutPut = new Thread() {
        // public void run() {
        // while (true) {
        // try {
        // os.write((bufferedReader.readLine() + "\n").getBytes());
        // os.flush();
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // }
        // }
        // };

        threadError.start();
        threadInput.start();
        Thread.sleep(1000);
//        threadError.join();
//        threadInput.join();
//        process.waitFor();
//        process.destroy();
//        process.waitFor();
        // threadOutPut.start();
    }
}